package com.jin.webvideo.base.linkedfile.util;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URL;
import java.net.URLConnection;

public class InputStreamUtils {

    public static InputStream getInputStreamByURI(URI uri, int maxDirect) throws IOException {
        if (maxDirect <= 0) {
            maxDirect = 3;
        }
        URL url = uri.toURL();
        URLConnection c = url.openConnection();
        while (maxDirect > 0 && c instanceof HttpURLConnection con) {
            maxDirect--;
            if (con.getResponseCode() != 302) {
                break;
            }
            con.disconnect();
            url = new URL(con.getHeaderField("location"));
            c = url.openConnection();
        }
        if (maxDirect <= 0) {
            throw new IOException("the maximum number of redirects allowed has been exceeded");
        }
        return c.getInputStream();
    }
}
